Online-Academy
Look, Read, Understand, Apply

Duck Typing

Duck typing is a concept where the type or class of an object is less important than whether it has the methods and properties you need. The name comes from the phrase: "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."

class Duck:
    def swim(self):
        return "Swin!"
    
    def walk(self):
        return "Walking like a duck"

class Person:
    def swim(self):
        return "I can swim too!"
    
    def walk(self):
        return "Walking like a human who mimics ducks"

def make_it_swim(obj):
    # Doesn't care about the type, just that it has a 'swim' method
    print(obj.swim())

# Both work because both have a 'swim' method
duck = Duck()
person = Person()

make_it_swim(duck)    # Output: Quack!
make_it_swim(person)  # Output: I can quack too!

Advantages of Duck Typing

  • Flexibility: Functions work with any object that implements required methods
  • Code Reuse: Write once, use with many different types
  • Polymorphism: Achieved without inheritance
  • Less Boilerplate: No need for abstract base classes or interfaces
  • Easier Testing: Can use mock objects easily